package com.dmall.graph.bfs;

import com.dmall.graph.Graph;

import java.util.*;

/**
 * @author: xiao1.wang
 * @date: 2022/6/19 16:46
 */
public class USSSPath1 {
    private Graph G;
    private int[] pre;
    private int[] dis;
    private int s;

    public USSSPath1(Graph G, int s) {
        G.validateVertex(s);
        this.G = G;
        this.s = s;
        this.pre = new int[G.V()];
        Arrays.fill(this.pre, -1);
        this.dis = new int[G.V()];
        Arrays.fill(this.dis, -1);
        bfs(s);
    }

    private void bfs(int s) {
        pre[s] = s;
        dis[s] = 0;
        Queue<Integer> queue = new LinkedList<>();
        queue.add(s);
        while (!queue.isEmpty()) {
            Integer cur = queue.remove();
            for (Integer w : G.adj(cur)) {
                if (pre[w] == -1) {
                    pre[w] = cur;
                    dis[w] = dis[cur] + 1;
                    queue.add(w);
                }
            }
        }
    }

    public boolean isConnectedTo(int t) {
        G.validateVertex(t);
        return pre[t] != -1;
    }

    public int dis(int t) {
        G.validateVertex(t);
        return dis[t];
    }

    public Iterable<Integer> path(int t) {
        ArrayList<Integer> res = new ArrayList<>();
        if (!isConnectedTo(t)) {
            return res;
        }
        int cur = t;
        while (cur != s) {
            res.add(cur);
            cur = pre[cur];
        }
        res.add(s);
        Collections.reverse(res);
        return res;
    }

    public static void main(String[] args) {
        String filePath = USSSPath.class.getClassLoader().getResource("g.txt").getPath();
        Graph graph = new Graph(filePath);
        USSSPath1 path = new USSSPath1(graph, 0);
        System.out.println(path.isConnectedTo(6));
        System.out.println(path.isConnectedTo(5));
        System.out.println(path.dis(6));
        System.out.println(path.dis(5));
        System.out.println("1 -> 6 : " + path.path(6));
        System.out.println("1 -> 5 : " + path.path(5));
    }
}
